import numpy as np


#求解梯度
def numerical_gradient(f,x):
    h = 1e-4 #定义极小值
    grad = np.zeros_like(x) #待会用它来放梯度数据
    it = np.nditer(x,flags=['multi_index'],op_flags=['readwrite'])
    while not it.finished:
        idx = it.multi_index
        tmp_val = x[idx]
        x[idx] = float(tmp_val) + h
        fxh1 = f(x) #f(x+h)

        x[idx] = float(tmp_val) - h
        fxh2 = f(x) #f(x-h)
        grad[idx] = (fxh1 - fxh2)/(2*h)

        x[idx] = tmp_val #还原值
        it.iternext()

    return grad

